package com.zzl.study.nacos.config;

import com.zzl.study.nacos.condition.ConditionalOnNacosMultiDiscoveryEnabled;
import com.zzl.study.nacos.discovery.NacosMultiDiscoveryHeartBeatPublisher;
import com.zzl.study.nacos.properties.NacosMultiDiscoveryProperties;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * Nacos多注册中心服务发现心跳事件自动配置类
 *
 * @author: zhangzl
 * @date: 2025/7/16 15:39
 * @version: 1.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnDiscoveryEnabled
@ConditionalOnBlockingDiscoveryEnabled
@ConditionalOnNacosMultiDiscoveryEnabled
@AutoConfigureAfter(value = NacosMultiDiscoveryAutoConfiguration.class, name = "de.codecentric.boot.admin.server.cloud.config.AdminServerDiscoveryAutoConfiguration")
public class NacosMultiDiscoveryHeartBeatAutoConfiguration {

    /**
     * 向Spring容器注入一个Nacos多注册中心服务发现心跳事件发布器
     *
     * @param nacosMultiDiscoveryProperties Nacos多注册中心属性配置
     * @return Nacos多注册中心服务发现心跳事件发布器
     */
    @Bean
    @ConditionalOnMissingBean
    @Conditional(NacosMultiDiscoveryHeartBeatCondition.class)
    public NacosMultiDiscoveryHeartBeatPublisher nacosDiscoveryHeartBeatPublisher(NacosMultiDiscoveryProperties nacosMultiDiscoveryProperties) {
        return new NacosMultiDiscoveryHeartBeatPublisher(nacosMultiDiscoveryProperties);
    }

    /**
     * Nacos多注册中心服务发现心跳事件发布器装配条件判断类
     */
    private static class NacosMultiDiscoveryHeartBeatCondition extends AnyNestedCondition {

        NacosMultiDiscoveryHeartBeatCondition() {
            super(ConfigurationPhase.REGISTER_BEAN);
        }

        /**
         * Spring Cloud Gateway HeartBeat .
         */
        @ConditionalOnProperty(value = "spring.cloud.gateway.discovery.locator.enabled", matchIfMissing = false)
        static class GatewayLocatorHeartBeatEnabled {
        }

        /**
         * Spring Boot Admin HeartBeat .
         */
        @ConditionalOnBean(type = "de.codecentric.boot.admin.server.cloud.discovery.InstanceDiscoveryListener")
        static class SpringBootAdminHeartBeatEnabled {
        }

        /**
         * Nacos HeartBeat .
         */
        @ConditionalOnProperty(value = "spring.cloud.nacos.multi-discovery.heart-beat.enabled", matchIfMissing = false)
        static class NacosMultiDiscoveryHeartBeatEnabled {
        }

    }

}
